package com.oscar.ehome.view.pageview;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.oscar.ehome.R;
import com.oscar.ehome.base.C;
import com.oscar.ehome.base.activity.BaseActivity;
import com.oscar.ehome.base.fragment.adapter.CustomFragmentPagerAdapter;
import com.oscar.ehome.base.fragment.adapter.NoPreloadViewPager;
import com.oscar.ehome.bean.pagebean.ClassRoomBean;
import com.oscar.ehome.bean.pagebean.ClassRoomPrombleBean;
import com.oscar.ehome.bean.pagebean.ClassRoomVideoBean;
import com.oscar.ehome.presenter.ClassRoomPresenter;
import com.oscar.ehome.provider.gildeimage.GildeUtils;
import com.oscar.ehome.provider.videoPlay.NiceVideoPlayerManagers;
import com.oscar.ehome.provider.videoPlay.NiceVideoPlayers;
import com.oscar.ehome.provider.videoPlay.TxVideoPlayerControllers;
import com.oscar.ehome.utils.basethem.TintManager;
import com.oscar.ehome.utils.dowload.VideoFrameImageLoader;
import com.oscar.ehome.utils.system.SystemConfigFactory;
import com.oscar.ehome.utils.util.CommonUtils;
import com.oscar.ehome.utils.util.SystemBarTintManager;
import com.oscar.ehome.utils.util.ToastUtil;
import com.oscar.ehome.view.loginview.LoginActivity;
import com.oscar.ehome.view.pageview.view.ClassRoomContentFragment;
import com.oscar.ehome.view.pageview.view.ClassRoomView;
import com.xiao.nicevideoplayer.NiceVideoPlayer;

import org.apache.commons.lang.StringUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by juxing
 * author: MengWanhe
 * date: On 2017/9/15
 * 小课堂视频播放
 */

public class ClassRoomVideoActivity extends BaseActivity implements ClassRoomView, TxVideoPlayerControllers.SetFullScreenListener,
        NiceVideoPlayers.NiceCallBack, TxVideoPlayerControllers.SetNotFullScreenListener, NoPreloadViewPager.OnPageChangeListener, CompoundButton.OnCheckedChangeListener {

    /**
     * 返回
     */
    @BindView(R.id.title_img_back)
    ImageView titleImgBack;
    /**
     * 返回
     */
    @BindView(R.id.title_layout_left)
    RelativeLayout titleLayoutLeft;
    /**
     * 标题
     */
    @BindView(R.id.title_topbar)
    TextView titleTopbar;
    /**
     *
     */
    @BindView(R.id.basetitle_bar)
    RelativeLayout basetitleBar;
    /**
     * 视频播放器
     */
    @BindView(R.id.classroom_player)
    NiceVideoPlayers classroomPlayer;
    /**
     * 标题
     */
    @BindView(R.id.classroomvideo_tile)
    TextView classroomvideoTile;
    /**
     * 讲师
     */
    @BindView(R.id.classroomvideo_techer)
    TextView classroomvideoTecher;
    /**
     *
     */
    @BindView(R.id.classroom_content)
    RadioButton classroomContent;
    /**
     *
     */
    @BindView(R.id.classroom_promble)
    RadioButton classroomPromble;
    /**
     *
     */
    @BindView(R.id.classroom_tabs_rg)
    RadioGroup classroomTabsRg;
    /**
     *
     */
    @BindView(R.id.classroom_frg)
    NoPreloadViewPager classroomFrg;
    /**
     *
     */
    @BindView(R.id.classroom_edtext)
    EditText classroomEdtext;
    /**
     *
     */
    @BindView(R.id.classroom_send)
    Button classroomSend;
    /**
     *
     */
    @BindView(R.id.classroompdfimg)
    ImageView classroompdfimg;
    /**
     *
     */
    @BindView(R.id.comment_layout)
    RelativeLayout commentLayout;
    /**
     *
     */
    @BindView(R.id.classimg_layout)
    RelativeLayout classimgLayout;

    ClassRoomVideoBean bean;
    ClassRoomPresenter presenter;
    TxVideoPlayerControllers controller;
    VideoFrameImageLoader loader;
    SystemBarTintManager tintManager;
    /* 标记当视频暂停时播放位置 */
    private long intPositionWhenPause = -1;

    String content = "";
    String title = "";
    String teacher = "";
    String url = "";
    String knowledgeId = "";
    String medaitype = "";

    private List<Fragment> fragmentList = new ArrayList<Fragment>();
    CustomFragmentPagerAdapter adapter = null;
    private int currIndex = 0;
    private String token = "";
    int lawyer = 0;

    String messagebean = "";
    ClassRoomBean.ClassRoomListBean messbean;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_classroomvideo);
        setBaseBackground(ClassRoomVideoActivity.this);
        ButterKnife.bind(this);
        setColor();
        onClicks();
        initView();
        initPager();
    }

    /**
     * 设置颜色
     */
    public void setColor() {
        basetitleBar.setBackgroundColor(Color.parseColor(SystemConfigFactory.getInstance(ClassRoomVideoActivity.this).getSystemConfig().getColor()));
        classroomContent.setTextColor(Color.parseColor(SystemConfigFactory.getInstance(this).getSystemConfig().getColor()));
        classroomPromble.setTextColor(Color.parseColor(SystemConfigFactory.getInstance(this).getSystemConfig().getColor()));
        TintManager.setTint(classroomContent, Color.parseColor(SystemConfigFactory.getInstance(this).getSystemConfig().getColor()));
        TintManager.setTint(classroomPromble, Color.parseColor(SystemConfigFactory.getInstance(this).getSystemConfig().getColor()));
        TintManager.setTint(classroomSend, Color.parseColor(SystemConfigFactory.getInstance(this).getSystemConfig().getColor()));
    }

    /**
     * 点击事件
     */
    public void onClicks() {
        classroomContent.setOnCheckedChangeListener(this);
        classroomPromble.setOnCheckedChangeListener(this);
        classroomFrg.setOnPageChangeListener(this);
    }

    /**
     * 加载页面
     */
    public void initPager() {
        fragmentList.add(new ClassRoomContentFragment());
        fragmentList.add(new ClassRoomPrombleFragment());
        adapter = new CustomFragmentPagerAdapter(getSupportFragmentManager(), fragmentList);
        classroomFrg.setAdapter(adapter);
    }

    public void initView() {
        titleImgBack.setImageResource(R.mipmap.fanhui);
        titleImgBack.setVisibility(View.VISIBLE);


        presenter = new ClassRoomPresenter(this);
        token = SystemConfigFactory.getInstance(ClassRoomVideoActivity.this).getSystemConfig().getToken();

        lawyer = getIntent().getIntExtra("lawyer", 0);
        messagebean = getIntent().getStringExtra("messagebean");
        if (messagebean != null && !"".equals(messagebean)) {
            messbean = new Gson().fromJson(messagebean, ClassRoomBean.ClassRoomListBean.class);
        }
        if (messbean.getRemarks() != null) {
            content = messbean.getRemarks();
        }
        if (messbean.getTitle() != null) {
            title = messbean.getTitle();
        }
        if (messbean.getCreateBy() != null) {
            if (messbean.getCreateBy().getName() != null) {
                teacher = messbean.getCreateBy().getName();
            }
        }
        if (messbean.getMediaName() != null) {
            url = C.qiniu_ip + messbean.getMediaName();
        }
        if (messbean.getId() != null) {
            knowledgeId = messbean.getId();
        }
        if (messbean.getMediaType() != null) {
            medaitype = messbean.getMediaType();
        }
        titleTopbar.setText(title);
        if ("video/mp4".equals(medaitype)) {
            initData();
            setVideo();
            classimgLayout.setVisibility(View.GONE);
            classroomPlayer.setVisibility(View.VISIBLE);
        } else if ("application/pdf".equals(medaitype)) {
//            GildeUtils.imgLoadPic(ClassRoomVideoActivity.this, C.qiniu + messbean.getCoverPicture(), classroompdfimg, "net");
            GildeUtils.loadUrlImages(C.qiniu_ip + messbean.getCoverPicture(), classroompdfimg, ClassRoomVideoActivity.this);
            classimgLayout.setVisibility(View.VISIBLE);
            classroomPlayer.setVisibility(View.GONE);
        } else {
            classroompdfimg.setImageResource(R.mipmap.moren);
            classimgLayout.setVisibility(View.VISIBLE);
            classroomPlayer.setVisibility(View.GONE);
        }

        classroomvideoTile.setText(title);
        classroomvideoTecher.setText(teacher);

        if (lawyer == 0) {
            commentLayout.setVisibility(View.GONE);
        } else {
            commentLayout.setVisibility(View.VISIBLE);
        }

    }

    /**
     * 初始视频播放器
     */
    public void initData() {
        classroomPlayer.setPlayerType(NiceVideoPlayer.TYPE_NATIVE); // IjkPlayer or MediaPlayer
        controller = new TxVideoPlayerControllers(this);
        controller.setOnFullScreenClickListener(this);
        controller.setNotOnFullScreenClickListener(this);

    }

    /**
     * 发送问题
     */
    public void sendPromble() {
        if (classroomEdtext.getText().toString() != null && StringUtils.isNotEmpty(classroomEdtext.getText().toString())) {
            presenter.sendPromble(token, knowledgeId, classroomEdtext.getText().toString());
            showLoading();
        } else {
            ToastUtil.show(ClassRoomVideoActivity.this, "请先填写问题.");
        }
    }

    /**
     * 配置视频
     */
    public void setVideo() {
        String[] urls = {url};
        loader = new VideoFrameImageLoader(ClassRoomVideoActivity.this, urls);
        classroomPlayer.setUp(url, null);
        controller.setTitle(title);//这里设置视频的title
            /* ?vframe/jpg/offset/0/w/500/h/500 视频第一帧拼接的字符串 */
//        GildeUtils.imgLoadPic(ClassRoomVideoActivity.this, url + "?vframe/jpg/offset/0/w/500/h/500", controller.imageView(), "net");
        GildeUtils.loadUrlImages(url + "?vframe/jpg/offset/0/w/500/h/500", controller.imageView(), ClassRoomVideoActivity.this);
        classroomPlayer.setController(controller);

        classroomPlayer.setNiceCallBackClicksListener(this);
    }

    @OnClick({R.id.title_layout_left, R.id.classroom_send, R.id.classimg_layout})
    public void onViewClicked(View v) {
        switch (v.getId()) {
            case R.id.title_layout_left:
                finish();
                break;
            case R.id.classroom_send://发送
                sendPromble();
                break;
            case R.id.classimg_layout://pdf
                Intent intent = new Intent(ClassRoomVideoActivity.this, ClassRoomPdfActivity.class);
                intent.putExtra("url", url);
                startActivity(intent);
                break;
        }
    }

    @Override
    public void knowledgeList(ClassRoomBean result) {

    }

    @Override
    public void problemList(ClassRoomPrombleBean result) {
    }

    @Override
    public void sendpromble(String result) {

        dismissLoading();
        classroomEdtext.setText("");
        if (result != null) {
            ToastUtil.show(ClassRoomVideoActivity.this, result);
        }
    }

    @Override
    public void erroy() {
        dismissLoading();
        ToastUtil.show(ClassRoomVideoActivity.this, getString(R.string.erry));
    }

    @Override
    public void erry(String result) {
        dismissLoading();
        ToastUtil.show(ClassRoomVideoActivity.this, result);
        if (result.contains("过期")) {
            getSharedPreferences("appbase", Context.MODE_PRIVATE).edit().clear().commit();
            SystemConfigFactory.getInstance(ClassRoomVideoActivity.this).getSystemConfig().SetLogin(false);
            SystemConfigFactory.getInstance(ClassRoomVideoActivity.this).getSystemConfig().setIsFirst(true);
            Intent intent = new Intent(ClassRoomVideoActivity.this, LoginActivity.class);
            startActivity(intent);
            finish();
        }
    }

    /**
     * 横屏处理
     */
    @Override
    public void onFullScreenClick() {//横屏
        tintManager.setStatusBarTintResource(R.color.transparent);
    }

    /**
     * 页面暂停效果处理
     */
    @Override
    public void onPause() {
        super.onPause();
        if (classroomPlayer.isPlaying()) {
            intPositionWhenPause = classroomPlayer.getCurrentPosition();
            classroomPlayer.pause();
        }
    }


    /* 这里处理再次进入页面从上次暂停的位置播放 */
    @Override
    public void onResume() {
        super.onResume();
        if (intPositionWhenPause >= 0) {
            classroomPlayer.seekTo(intPositionWhenPause);
            //初始播放位置
            intPositionWhenPause = -1;
        }
    }

    // 按下Home键暂停播放，回到界面继续播放。
    @Override
    protected void onStop() {
        NiceVideoPlayerManagers.instance().suspendNiceVideoPlayer();
        super.onStop();
    }

    @Override
    protected void onRestart() {
        NiceVideoPlayerManagers.instance().resumeNiceVideoPlayer();
        super.onRestart();
    }


    // 按返回键
    // 当前是全屏或小窗口，需要先退出全屏或小窗口。
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!NiceVideoPlayerManagers.instance().onBackPressd()) {
                finish();
            } else {
                tintManager.setStatusBarTintColor(Color.parseColor(SystemConfigFactory.getInstance(ClassRoomVideoActivity.this).getSystemConfig().getColor()));
            }
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        // 很重要，在Activity和Fragment的onStop方法中一定要调用，释放的播放器。
        if (loader != null) {
            NiceVideoPlayerManagers.instance().releaseNiceVideoPlayer();
            loader.cancelTask();
        }
        super.onDestroy();
    }

    /**
     * 设置系统标题背景颜色
     *
     * @param act
     */
    public void setBaseBackground(Activity act) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            CommonUtils.setTranslucentStatus(true, act);
            tintManager = new SystemBarTintManager(act);
            tintManager.setStatusBarTintEnabled(true);
            tintManager.setStatusBarTintColor(Color.parseColor(SystemConfigFactory.getInstance(ClassRoomVideoActivity.this).getSystemConfig().getColor()));
        }
    }

    @Override
    public void start() {

    }

    @Override
    public void onNotFullScreenClick() {
        tintManager.setStatusBarTintColor(Color.parseColor(SystemConfigFactory.getInstance(ClassRoomVideoActivity.this).getSystemConfig().getColor()));
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (classroomContent.isChecked()) {
            classroomFrg.setCurrentItem(0);
            classroomContent.setTextColor(Color.parseColor(SystemConfigFactory.getInstance(this).getSystemConfig().getColor()));
            classroomPromble.setTextColor(Color.parseColor("#999999"));
        } else if (classroomPromble.isChecked()) {
            classroomFrg.setCurrentItem(1);
            classroomPromble.setTextColor(Color.parseColor(SystemConfigFactory.getInstance(this).getSystemConfig().getColor()));
            classroomContent.setTextColor(Color.parseColor("#999999"));
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        switch (position) {
            case 0:
                if (currIndex == 1) {//从页卡1跳转转到页卡2
                    classroomContent.setChecked(true);
                    classroomPromble.setChecked(false);
                } else if (currIndex == 2) {// 从页卡1跳转转到页卡3
                    classroomContent.setChecked(true);
                    classroomPromble.setChecked(false);
                }
                break;
            case 1:
                if (currIndex == 0) {//从页卡1跳转转到页卡2
                    classroomContent.setChecked(false);
                    classroomPromble.setChecked(true);
                } else if (currIndex == 2) { // 从页卡1跳转转到页卡2
                    classroomContent.setChecked(false);
                    classroomPromble.setChecked(true);
                }
                break;
        }
        currIndex = position;
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}
